package com.genius.framework.multitenancy.config;

import com.genius.framework.multitenancy.provider.MultiTenantContextProvider;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class TenantCleanInterceptor implements HandlerInterceptor {

    private ThreadLocal<String> key = new ThreadLocal<>();
    private ThreadLocal<Long> time = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (request.getServletPath() != null && request.getServletPath().startsWith(FileServerConfig.pathPattern)) {
            response.setCharacterEncoding("UTF-8");
            key.set(UUID.randomUUID().toString());
            time.set(System.currentTimeMillis());
            String filePath = request.getServletPath().replace(FileServerConfig.pathPattern, "");
            System.out.println("key: " + key.get() + ", start: " + filePath);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (request.getServletPath() != null && request.getServletPath().startsWith(FileServerConfig.pathPattern)) {
            response.setCharacterEncoding("UTF-8");
            String filePath = request.getServletPath().replace(FileServerConfig.pathPattern, "");
            if (response.getStatus() == 404) {
                System.out.println("key: " + key.get() + ", not found: " + filePath);
            }
            System.out.println("key: " + key.get() + ", end: " + filePath + ", spend: " + (System.currentTimeMillis() - time.get()));
        } else {
            MultiTenantContextProvider.cleanCurrentTenant();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        MultiTenantContextProvider.cleanCurrentTenant();
    }
}